/**
 * API工具类，用于封装与云函数的交互
 */

// 调用云函数的统一接口
const callCloudFunction = async (name, data = {}) => {
  try {
    const result = await uniCloud.callFunction({
      name,
      data,
    });
    return result.result;
  } catch (error) {
    console.error(`调用云函数 ${name} 失败:`, error);
    throw error;
  }
};

// 登录
export const login = async (username, password) => {
  return await callCloudFunction("login", { username, password });
};

// 初始化管理员账号
export const initAdminUser = async () => {
  return await callCloudFunction("initAdminUser");
};

// 获取用户信息
export const getUserInfo = async (userId) => {
  return await callCloudFunction("getUserInfo", { userId });
};

// 获取用户列表
export const getUserList = async (params = {}) => {
  return await callCloudFunction("getUserList", params);
};

// 更新用户信息
export const updateUserInfo = async (userId, userInfo) => {
  return await callCloudFunction("updateUserInfo", { userId, userInfo });
};

// 获取仪表盘数据
export const getDashboardData = async () => {
  return await callCloudFunction("getDashboardData");
};

// 检查登录状态并获取当前用户信息
export const checkLoginStatus = () => {
  const token = uni.getStorageSync("token");
  const isLoggedIn = uni.getStorageSync("isLoggedIn");
  const userInfo = uni.getStorageSync("userInfo");

  return {
    isLoggedIn: !!isLoggedIn,
    token,
    userInfo,
  };
};

// 退出登录
export const logout = () => {
  uni.removeStorageSync("token");
  uni.removeStorageSync("isLoggedIn");
  uni.removeStorageSync("userInfo");
};
